import React, { useEffect, useRef } from 'react';
import { useLatest } from 'ahooks';

import { Map } from 'l3d';
import { Viewer, WebMercatorProjection } from 'cesium';

interface L3DMapProps extends React.HTMLAttributes<HTMLDivElement> {
  mapOptions?: Viewer.ConstructorOptions;
  onSetMap?: (l3dMap?: Map) => void;
}

function L3DMap(props: L3DMapProps) {
  const { onSetMap, mapOptions, ...divProps } = props;

  const mapContainer = useRef<HTMLDivElement>(null);
  const setMapRef = useLatest(onSetMap);

  useEffect(() => {
    if (!mapContainer.current) return;

    const l3dMap = new Map({
      dom: mapContainer.current,
      options: {
        selectionIndicator: true,
        mapProjection: new WebMercatorProjection(),
        ...mapOptions,
      },
    });

    const handler = setMapRef.current;
    handler && handler(l3dMap);

    // @ts-ignore debug
    window.l3dMap = l3dMap;

    return () => {
      handler && handler(undefined);
      setTimeout(() => l3dMap.destroy(), 0);
    };
  }, [setMapRef]);

  return <div ref={mapContainer} style={{ height: '100%' }} {...divProps} />;
}

export default React.memo(L3DMap);
